package com.information.service;

import com.information.entity.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.htmq.core.InforSuiteHTMQTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserEventProducer {
    
    public static final String USER_EVENT_TOPIC = "user-event";

    @Autowired
    private InforSuiteHTMQTemplate<String, String> inforsuiteHTMQTemplate;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    /**
     * 发送用户事件到消息队列
     */
    public void sendUserEvent(String operationType, User user, String operatedBy) {
        try {
            Map<String, Object> eventData = new HashMap<>();
            eventData.put("operationType", operationType);
            eventData.put("operatedBy", operatedBy);
            eventData.put("timestamp", System.currentTimeMillis());
            
            // 简化用户数据，避免循环引用
            Map<String, Object> userData = new HashMap<>();
            userData.put("id", user.getId());
            userData.put("username", user.getUsername());
            userData.put("name", user.getName());
            userData.put("email", user.getEmail());
            userData.put("phone", user.getPhone());
            userData.put("age", user.getAge());
            userData.put("gender", user.getGender());
            userData.put("address", user.getAddress());
            userData.put("role", user.getRole() != null ? user.getRole().name() : null);
            userData.put("status", user.getStatus() != null ? user.getStatus().name() : null);
            
            eventData.put("user", userData);
            
            String message = objectMapper.writeValueAsString(eventData);

            inforsuiteHTMQTemplate.send(USER_EVENT_TOPIC, message);

        } catch (Exception e) {
            System.err.println("发送用户事件到消息队列失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}